package com.jacen.fzxs.dao.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.jacen.fzxs.dao.IUserDao;
import com.jacen.fzxs.entity.UserEntity;
import com.jacen.fzxs.util.SqlCondition;
import com.jacen.fzxs.util.Utils;


/**
 * 用户dao
 * @author Jacen
 * 2014年9月10日 下午9:06:10
 */
@Repository
public class UserDao extends BaseDao<UserEntity> implements IUserDao {
	
	@Override
	public List<UserEntity> getPage(int start, int size, Map<String, String> params) {
		SqlCondition cond = getPageCondition(params);
		String sql = "SELECT * from t_user where 1=1 %s ";
		sql = String.format(sql, cond.getCondition());
		sql = SqlCondition.pageSql(sql, start, size);
		return executeForList(sql, cond.getParams().toArray());
	}
	
	public int getCount(Map<String, ? extends Object> paramMap) throws SQLException {
		SqlCondition cond = getPageCondition(paramMap);
		String sql = "select count(1) from t_user where 1=1 %s";
		sql = String.format(sql, cond.getCondition());
		return Long.valueOf(executeForLong(sql, cond.getParams().toArray())).intValue();
	}
	
	private SqlCondition getPageCondition(
			Map<String, ? extends Object> mapParams) {
		SqlCondition cond = new SqlCondition();
		if (Utils.paramIsNotEmpty(mapParams.get("userName")))
			cond.and().equal("userName", mapParams.get("userName"));
		return cond;
	}

	@Override
	public List<UserEntity> getList(Map<String, String> params) {
		SqlCondition cond = getPageCondition(params);
		String sql = "";
		sql = String.format(sql, cond.getCondition());
		return executeForList(sql);
	}
	
	@Override
	public List<UserEntity> getListByRoleId(String roleId) throws Exception {
		String sql = "select t.* from t_user t left join t_role_user tt on t.id = tt.user_id where tt.role_id = '%s'";
		sql = String.format(sql, roleId);
		return  executeForList(sql);
	}

	@Override
	public UserEntity login(String username, String password) {
		String sql = "select * from t_user t where username = '%s' and password = '%s'";
		sql = String.format(sql, username, password);
		return executeForObject(sql);
	}

	public List<UserEntity> getPage(int start, int size) {
		String sql = "select  t.* from t_user t where t.id not IN (select DISTINCT t2.user_id from t_role_user t2) ";
		sql = SqlCondition.pageSql(sql, start, size);
		return executeForList(sql);
	}

	public int getCount() {
		String sql = "select count(1) from t_user t where t.id not IN (select DISTINCT t2.user_id from t_role_user t2) ";
		return Long.valueOf(executeForLong(sql)).intValue();
	}

	

}
